import { effects } from 'dva-core/saga';
import { storage } from '@doctorwork/saga';
import { setNavigationBarTitle } from '@doctorwork/utils';
/**
 * 金额转换
 */
export const toMoneyFormat = function (value) {
    if (!value) {
        return '0.00';
    }
    value = value / 100;
    value = value.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
    return value;
};
export const numberFormat = function (value) {
    value = value.toString() || '0';
    value = value.replace(/\d(?=(\d{3})+\.)/g, '$&,');
    return value;
};

/**
 * 时间戳转时间
 * @param timestamp 时间戳
 * @param isFull 是否需要时分秒
 * @return Promise 对象
 */
export const timeFormat = (timestamp, format = 'YYYY-MM-DD hh:mm:ss') => {
    if (!timestamp) return '';
    var date = new Date(getTimeStamp(timestamp) * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear();
    var M =
        date.getMonth() + 1 >= 10
            ? date.getMonth() + 1
            : '0' + (date.getMonth() + 1);
    var D = date.getDate() >= 10 ? date.getDate() : '0' + date.getDate();
    var h = date.getHours() >= 10 ? date.getHours() : '0' + date.getHours();
    var m =
        date.getMinutes() >= 10 ? date.getMinutes() : '0' + date.getMinutes();
    var s =
        date.getSeconds() >= 10 ? date.getSeconds() : '0' + date.getSeconds();

    var value = format
        .replace('YYYY', Y)
        .replace('MM', M)
        .replace('DD', D)
        .replace('hh', h)
        .replace('mm', m)
        .replace('ss', s);
    return value;
};

/**
 * 函数节流
 * @param {*} method 需要执行的函数
 * @param {*} duration 间隔时间
 */
export const throttle = (function() {
    var begin = Date.now();
    return function(method, duration) {
        var context = this,
            args = arguments,
            current = Date.now();
        if (current - begin >= duration) {
            method.apply(context, args);
            begin = current;
        }
    };
})();
/* 
    underscore.debounce 函数防抖
    使用： 在constructor中绑定 this.doSth = debounce(this.doSth.bind(this),time)即可
*/
export const debounce = function(func, wait, immediate){
    var timeout, context, args, result, timestamp
    var later = function(){
        // 比较时间戳
        var last = new Date().getTime() - timestamp
        
        if (last < wait && last >= 0) {
            // 重新设置时间间隔，并且时间间隔缩小
            timeout = setTimeout(later, wait - last)
        } else {
            timeout = null
            if(!immediate) {
                // 传入了以后只会执行一次 不会再次执行
                result = func.apply(context, args)
                if(!timeout) context = args = null  
            }
        }
    }

    return function(){
        context = this
        args =  arguments    // 这是里面这个函数的参数
        timestamp = new Date().getTime()
        // 开关 立即执行为true，定时器为null时
        var callNow = immediate && !timeout
        // 创建一个定时器
        if(!timeout) timeout = setTimeout(later, wait)
        // 如果传入了immediate 在一开始会立即执行，并且在wait时间内不会再次执行
        // 比如防止按钮的连续点击
        // 而比如窗口的大小变化等连续变化后再执行，则不需出传这个参数
        if(callNow) {
            result = func.apply(context, args)
            context = args = null   // 释放闭包的不必要变量
        }
        return result
    }
}

//保持时间为两位数
export const checkTime = function (time) {
    let tempTime = time;
    if (time < 10) {
        tempTime = '0' + time;
    }
    return tempTime;
};

//校验是否登录
export const isLogin = function* () {
    const userInfo = yield effects.put.resolve(storage.get('userInfo'));
    const authToken = yield effects.put.resolve(storage.get('authToken'));
    if (userInfo && authToken && userInfo.phone) {
        return true;
    } else {
        return false;
    }
};

/**
 * 解析请求参数
 * @param {*} url
 */
export const parseQuery = url => {
    let query = {};
    if (url.indexOf('?') >= 0) {
        url.split('?')[1]
            .split('&')
            .forEach(entry => {
                let _query = entry.split('=');
                query[_query[0]] = _query[1];
            });
    }
    return query;
};

/**
 * 倒计时
 * @param {*} endTime 倒计时结束时间, 格式YYYY-MM-DD HH:mm:ss
 * @param {*} endTime 倒计时开始时间, 格式YYYY-MM-DD HH:mm:ss
 * @param {*} offset 倒计时时间偏差，以秒为单位
 * @return 返回时分秒，日会转换成小时
 */
export const countdownTime = (
    endTimeStr,
    startTimeStr = new Date(),
    offset = 0
) => {
    if (!endTimeStr) return '';
    const endTime = getTimeStamp(endTimeStr) + offset;
    const startTime = getTimeStamp(startTimeStr);
    let timestamp = endTime - startTime;
    if (timestamp < 0) return '';
    let h = Math.floor(timestamp / 3600);
    let m = Math.floor((timestamp % 3600) / 60);
    let s = Math.floor(timestamp % 60);
    h = h > 9 ? h : '0' + h;
    m = m > 9 ? m : '0' + m;
    s = s > 9 ? s : '0' + s;
    return `${h}:${m}:${s}`;
};
/**
 * 获取时间戳
 * @param {*} time
 * 参数类型： 1，时间字符串 YYYY-MM-DD ,2 时间对象, 3 时间戳，精确到秒
 */
export const getTimeStamp = time => {
    if (typeof time == 'string') {
        var timeArr = time.split(/[- : \/]/);
        let timeObj = new Date(
            timeArr[0],
            timeArr[1] - 1,
            timeArr[2],
            timeArr[3],
            timeArr[4],
            timeArr[5]
        );
        let timeStamp = Math.ceil(timeObj.getTime() / 1000);
        return timeStamp;
    } else if (typeof time == 'object') {
        return Math.ceil(time.getTime() / 1000);
    } else {
        let timeStr = time.toString() || '';
        return timeStr.length > 10 ? Math.ceil(time / 1000) : time;
    }
};

/**
 * 返回到某一级页面
 * @param {*} url
 */
export const navigateBackTo = url => {
    var pagelist = getCurrentPages();
    var len = pagelist.length;

    for (var i = 0; i < len; i++) {
        if (pagelist[i].route.indexOf(url) >= 0) {
            //看路由里面是否有 对应的url
            wx.navigateBack({
                delta: len - i - 1
            });
        }
    }
};

export const promisify = (func, opts) => {
    return new Promise((resolve, reject) => {
        func({
            ...opts,
            success: resolve,
            fail: reject
        });
    });
};

//模拟cookie带实效性的存储
export const cookie = (function(){
    var store = {}; 
    /**
     * 获取存储内容
     * @param {*} args ，可以传入多个参数，如果只有一个参数则直接返回值
     */
    function get(){
        let data = {} ;
        let now = Date.now();
        let args = Array.prototype.slice.call(arguments);
        args.forEach( key => {
            if(store[key] && (!store[key].expire || store[key].expire > now) ){
                data[key] = store[key].value;
            }else{
                delete store[key];//过期删除
            }
        });
        return args.length==1 ? data[args[0]]: data;
    }
    /**
     * 设置存储值
     * @param {*} key 
     * @param {*} value 
     * @param {*} duration 存储时长，单位毫秒，过期将无法访问
     */
    function set(key,value,duration){
        store[key] = {
            value
        };
        if(duration){
            let timestamp = Date.now();
            store[key].expire = timestamp+duration;
        }
    }
    return {
        get , set
    };
})();
